<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\Administrator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;

class ActivityLogController extends Controller
{
    public function list(Request $request)
    {
        return $this->response->array(
            ActivityLog::query()
                ->select(['id', 'description', 'causer_id', 'causer_type', 'created_at', 'properties'])
                ->with('causer:id,account')
                ->when($request->get('account'), function (Builder $query, $account) {
                    $accountIds = Administrator::query()
                        ->where('account', 'like', '%' . $account . '%')
                        ->orWhere('real_name', 'like', '%' . $account . '%')
                        ->get(['id']);

                    $query->whereIn('causer_id', $accountIds);
                })
                ->when($request->get('created_at_begin'), function (Builder $query, $createdAtBegin) {
                    $query->where('created_at', '>=', $createdAtBegin);
                })
                ->when($request->get('created_at_end'), function (Builder $query, $createdAtEnd) {
                    $query->where('created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
                })
                ->orderByDesc('created_at')
                ->paginate());
    }
}
